// internal/planner/logical/builder.go
package logical

import (
    "fmt"
    "NumberBase/internal/parser/ast"
    "NumberBase/internal/planner/types"
    "NumberBase/internal/planner/expression"
)

// Builder 负责从AST构建逻辑计划
type Builder struct {
    exprBuilder *expression.Builder
    // 后续可能需要catalog引用
}

// NewBuilder 创建逻辑计划构建器
func NewBuilder() *Builder {
    return &Builder{
        exprBuilder: expression.NewBuilder(),
    }
}

// Build 从AST构建逻辑计划
func (b *Builder) Build(stmt ast.Statement) (types.LogicalPlan, error) {
    switch s := stmt.(type) {
    case *ast.SelectStatement:
        return b.buildSelect(s)
    // Todo: 其他语句类型...
    default:
        return nil, fmt.Errorf("不支持的语句类型: %T", stmt)
    }
}

// 构建SELECT查询计划
func (b *Builder) buildSelect(stmt *ast.SelectStatement) (types.LogicalPlan, error) {
    // 1. 构建表扫描
    scan := &TableScan{
        TableName: stmt.TableName,
        SchemaRef: createTableSchema(stmt.TableName), // 简化，实际应查询catalog
    }
    
    var plan types.LogicalPlan = scan
    
    // 2. 如果有WHERE，添加过滤
    if stmt.Where != nil {
        condition, err := b.exprBuilder.Build(stmt.Where)
        if err != nil {
            return nil, fmt.Errorf("构建WHERE条件出错: %w", err)
        }
        
        plan = &Filter{
            Input:     plan,
            Condition: condition,
        }
    }
    
    // 3. 添加投影
    projections, outSchema, err := b.buildProjectionList(stmt.Columns, plan.Schema())
    if err != nil {
        return nil, fmt.Errorf("构建投影列表出错: %w", err)
    }
    
    plan = &Projection{
        Input:        plan,
        Expressions:  projections,
        OutputSchema: outSchema,
    }
    
    return plan, nil
}

// 辅助方法:构建投影列表
func (b *Builder) buildProjectionList(
    columns []ast.Expression, 
    inputSchema *types.Schema) ([]types.Expression, *types.Schema, error) {
    
    // 检查是否是 SELECT *
    if len(columns) == 1 {
        if _, isAsterisk := columns[0].(*ast.AsteriskExpression); isAsterisk {
            // 全部列，返回输入schema
            return []types.Expression{}, inputSchema, nil
        }
    }
    
    // 构建单独的投影表达式
    var exprs []types.Expression
    var outputColumns []*types.Column
    
    for _, col := range columns {
        expr, err := b.exprBuilder.Build(col)
        if err != nil {
            return nil, nil, err
        }
        
        exprs = append(exprs, expr)
        
        // 基于表达式类型确定输出列
        if colRef, ok := expr.(*expression.ColumnRef); ok {
            outputColumns = append(outputColumns, colRef.Column)
        } else {
            // 对于计算列，创建新的列定义
            outputColumns = append(outputColumns, &types.Column{
                Name:     expr.String(),
                Table:    "",
                DataType: expr.ResultType(),
            })
        }
    }
    
    return exprs, &types.Schema{Columns: outputColumns}, nil
}

// 简化的schema创建
func createTableSchema(tableName string) *types.Schema {
    // 实际应从catalog获取
    return &types.Schema{
        Columns: []*types.Column{
            {Name: "id", Table: tableName, DataType: types.TypeInteger},
            {Name: "name", Table: tableName, DataType: types.TypeString},
            {Name: "age", Table: tableName, DataType: types.TypeInteger},
        },
    }
}